# -*- coding: utf-8 -*-
import json
import re
import sys
from openpyxl import Workbook

import pandas as pd

from extract_attributes.main import read_txt_file, read_pdf_from_file, get_allFile_from_folder
from pdf2excelv1.outInterface import get_answer

"""
1、文本分割成句子(text2sentence)
2、获得句子的类型（extract_type）
3、获得实体属性映射(filter_mapping.json)
4、根据属性进行预测(extract_attributes)
"""


def extract(pdf_file_path):
    file_content = read_pdf_from_file(pdf_file_path)
    # 文本分割成句子
    sentences = text2sentence(file_content)

    result = []
    for sentence in sentences:
        sentence = sentence.replace("\n", "")
        ask_type = "根据文本内容:“" + str(sentence) + "”回答实体类型是什么"
        sentence_type = get_answer(ask_type)
        # 映射表是通过手都筛选出来的
        mapping_dic = json.load(open(r"filter_mapping.json", 'r', encoding='utf-8'))
        try:
            values = mapping_dic[sentence_type]
            for value in values:
                ask_result = "根据文本内容:“" + str(sentence) + "”回答" + str(value) + "是什么"
                answer = get_answer(ask_result)
                result.append([sentence, sentence_type, value, answer])
        except:
            print(sentence_type)
    wirte_excel(result, filename="result.xlsx")


'''
获得实体属性映射
1、读文件
2、D列是实体和E列是属性
    1、利用字典，D是key，E是value
'''


def set_encoder(obj):
    if isinstance(obj, set):
        return list(obj)
    raise TypeError(f'Object of type {obj.__class__.__name__} is not JSON serializable')


def get_mapping():
    folder_path = r"指南知识图谱三元组提取"
    allFile = get_allFile_from_folder(folder_path, file_type="xlsx")
    dic = {}
    for file_path in allFile:
        df = pd.read_excel(file_path, engine='openpyxl')
        entitys = df['entityTag']
        propertys = df['property']
        for i, entity in enumerate(entitys):
            # 找到所有的临床问题
            if entity not in dic:
                dic[entity] = {propertys[i]}
            else:
                dic[entity].update({propertys[i]})

    with open(r'mapping.json', "a+", encoding="utf-8") as f:
        f.write(json.dumps(dic, ensure_ascii=False) + "\n")


def wirte_excel(data, filename):
    # 创建一个新的 Excel 文件
    workbook = Workbook()
    # 选择默认活动表单
    sheet = workbook.active

    # 将二维数组写入表格中
    for row in data:
        sheet.append(row)

    # 保存 Excel 文件
    workbook.save(filename=filename)


# 将文本分割成句子
def text2sentence(file_content):
    sentence_regex = re.compile(r'[？。！!]')
    sentences = sentence_regex.split(file_content)
    punctuation = sentence_regex.findall(file_content)
    sentences = [x + y for x, y in zip(sentences, punctuation)]
    return sentences



